import router from '@/router'
import Layout from '@/views/placeholder/layout.vue'
import Center from '@/views/placeholder/center.vue'
import dashboard from '@/router/main/dashboard/dashboard'
import { markRaw } from 'vue'

export function mapMenusToRoutes(menuList: any[]) {
  // import.meta.glob()为vite加载本地文件的方法，与webpack的require不同，注意区分
  const files: Record<string, any> = import.meta.glob(
    '../router/main/**/*.ts',
    {
      // 这里为true代表立即拿到结果，返回模块结果
      eager: true
    }
  )
  for (const key in files) {
    const module = files[key]
    recurseReplaceCpn(menuList, module.default)
  }

  // 动态添加菜单
  router.addRoute('main', dashboard)
  for (const menu of menuList) {
    router.addRoute('main', menu)
  }

  // 递归替换component属性 /goods/goodsType  为  () => import("/src/views/main/goods/goodsType.vue")
  function recurseReplaceCpn(menuList: any[], curMenu: any) {
    for (const menu of menuList) {
      if (!menu.component) {
        menu.component = markRaw(Center)
      }
      if (menu.component === 'Layout') {
        menu.component = markRaw(Layout)
      }
      if (menu.children?.length > 0) {
        // console.log(menu.children)
        // const firstMenuUrl = menu.children[0].path
        // const firstMenu = {
        //   path: '',
        //   redirect: firstMenuUrl
        // }
        // console.log(firstMenuUrl)
        // menu.children.unshift(firstMenu)
        recurseReplaceCpn(menu.children, curMenu)
      } else {
        if (!menu.name) return
        if (
          menu.name.split('/').pop().toUpperCase() ===
          curMenu.name.toUpperCase()
        ) {
          menu.component = curMenu.component
          break
        }
      }
    }
  }
}
